package org.example.supplychain.controller;

import jakarta.servlet.http.HttpSession;
import org.example.supplychain.domain.User;
import org.example.supplychain.service.BackupScheduleService;
import org.example.supplychain.service.MetricsExporterService;
import org.example.supplychain.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.stream.Stream;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    BackupScheduleService backupScheduleService;
    @Autowired
    MetricsExporterService metricsExporterService;

    @GetMapping("")
    public String home(Model model) {
        model.addAttribute("userPage", 1);
        return "userManagement";
    }

    @GetMapping("/sysAdmin")
    public String sysAdmin(Model model) {
        model.addAttribute("userPage", 3);
        return "userManagement";
    }

    /**
     * 创建用户
     *
     * @param userName 用户名
     * @param password 密码
     * @param nickname 昵称
     * @param phone    电话
     * @param role     角色
     */
    @PostMapping("/create")
    public String addUser(@RequestParam("userName") String userName, @RequestParam("password") String password,
                          @RequestParam("nickName") String nickname, @RequestParam("phone") String phone,
                          @RequestParam("userRole") String role, Model model) {
        User user = new User();
        User tmp= userService.getUserByUserName(userName);
        if(tmp!=null){
            model.addAttribute("error", "用户名已存在");
        }else {
            user.setUserName(userName);
            user.setPassword(password);
            user.setNickname(nickname);
            user.setPhone(phone);
            user.setRole(role);
            user.setCreateDate(new java.util.Date());
            userService.addUser(user);
        }
        model.addAttribute("userPage", 1);
        return "userManagement";
    }

    /**
     * 通过用户名删除用户
     *
     * @param userName 用户名
     */
    @PostMapping("/delete")
    public String deleteUserByUserName(@RequestParam("username") String userName,HttpSession session, Model model) {
        if(userName.equals(session.getAttribute("name"))){
            model.addAttribute("deleteError", "不能删除自己");
        }else {
            userService.deleteUserByUserName(userName);
        }
        model.addAttribute("userPage", 1);
        return "userManagement";
    }

    /**
     * 更新用户
     *
     * @param userName 用户名
     * @param phone    电话
     * @param role     角色
     */
    @PostMapping("/update")
    public String updateUser(@RequestParam("userName") String userName, @RequestParam("password") String passwd,
                             @RequestParam("nickName") String nickName, @RequestParam("phone") String phone,
                             @RequestParam("userRole") String role, Model model) {
        User user = new User();
        user.setUserName(userName);
        user.setPassword(passwd);
        user.setNickname(nickName);
        user.setPhone(phone);
        user.setRole(role);
        userService.updateUser(user);
        model.addAttribute("userPage", 1);

        return "userManagement";
    }

    /**
     * 通过用户名获取用户
     *
     * @param userName 用户名
     * @return 用户
     */
    @RequestMapping("/detail")
    public User getUserByUserName(@RequestParam("username") String userName) {
        return userService.getUserByUserName(userName);
    }

    /**
     * 获取所有用户
     *
     * @return 所有用户
     */
    @RequestMapping("/list")
    public String getAllUsers(@RequestParam("userName") String userName, @RequestParam("userRole") String role,
                              @RequestParam("phone") String phone, @RequestParam("nickName") String nickName, HttpSession session, Model model) {
        List<User> userList = userService.getAllUsers();
        Stream<User> tmp = userList.stream();
        if (!userName.isEmpty()) {
            tmp = tmp.filter(user -> user.getUserName().contains(userName));
        }
        if (!role.isEmpty()) {
            tmp = tmp.filter(user -> user.getRole().contains(role));
        }
        if (!phone.isEmpty()) {
            tmp = tmp.filter(user -> user.getPhone().contains(phone));
        }
        if (!nickName.isEmpty()) {
            tmp = tmp.filter(user -> user.getNickname().contains(nickName));
        }
        model.addAttribute("usersQuery", tmp.toList());
        model.addAttribute("userPage", 1);
        return "userManagement";
    }

    @PostMapping("/backup")
    public String backup(Model model) {
        backupScheduleService.backUpDataBase();
        model.addAttribute("userPage", 3);
        return "userManagement";
    }

    @PostMapping("/sysStatus")
    public String sysStatus(HttpSession session,Model model) {
        RestTemplate restTemplate= new RestTemplate();
        ResponseEntity<String> healthResponse = restTemplate.getForEntity("http://localhost:8080/actuator/health", String.class);
        String healthData = "Health: " + healthResponse.getBody() + "\n";
        model.addAttribute("status", metricsExporterService.checkSystemStatus(healthData));
        model.addAttribute("database", metricsExporterService.checkDatabaseStatus(healthData));
        model.addAttribute("disk", metricsExporterService.calculateDiskSpaceUsage(healthData));
        model.addAttribute("error", metricsExporterService.getSystemErrorCount());

//        session.setAttribute("status", metricsExporterService.checkSystemStatus(healthData));
//        session.setAttribute("database", metricsExporterService.checkDatabaseStatus(healthData));
//        session.setAttribute("disk", metricsExporterService.calculateDiskSpaceUsage(healthData));
//        session.setAttribute("error", metricsExporterService.getSystemErrorCount());
        model.addAttribute("userPage", 3);
        return "userManagement";
    }
}
